﻿using System.Drawing;
using System.IO;
using System.Windows.Forms;

using Elifart.Editor.Properties;
using Elifart.Library;

namespace Elifart.Editor.GeneralControls
{
    public partial class FileChooser : Form
    {
        #region Constructor

        public FileChooser(string selectedItemName, string imagesPath)
        {
            this.ImagesPath = imagesPath;            
            this._selectedItemName = selectedItemName;
            this.SelectedImage = selectedItemName;
            InitializeComponent();
            this.CancelAllowed = true;
            this.OKAllowed = false;
        }

        #endregion

        #region Attributes and Properties

        private string _imagesPath;
        public string ImagesPath
        {
            get { return this._imagesPath; }
            private set { this._imagesPath = value; }
        }

        private string _selectedImage;
        public string SelectedImage
        {
            get { return this._selectedImage; }
            set 
            { 
                this._selectedImage = value; 
                if (string.Compare(this._selectedImage, "None") == 0)
                    this._selectedImage = string.Empty;
            }
        }

        private bool _cancelAllowed;
        private bool CancelAllowed
        {
            get { return this._cancelAllowed; }
            set 
            { 
                this._cancelAllowed = value;
                this.btn_cancel.Enabled = this._cancelAllowed;
            }
        }

        private bool _okAllowed;
        private bool OKAllowed
        {
            get { return this._okAllowed; }
            set 
            { 
                this._okAllowed = value;
                this.btn_ok.Enabled = this._okAllowed;
            }
        }

        #endregion

        #region Private Fields

        private string _selectedItemName;

        #endregion

        #region Private Methods

        private void CopyImage(FileInfo imageFileInfo)
        {
            if (!Directory.Exists(this.ImagesPath))
                Directory.CreateDirectory(this.ImagesPath);

            string destinationName = Path.Combine(this.ImagesPath, imageFileInfo.Name);
            File.Copy(imageFileInfo.FullName, destinationName, true);
        }

        private void CreateNoneItem()
        {
            ListViewItem listViewItem = new ListViewItem();
            listViewItem.Name = "None";
            listViewItem.Text = "Nenhum";
            listViewItem.ImageIndex = 0;

            this.iml_associationFlags.Images.Add(Resources.none);
            this.lvw_images.Items.Add(listViewItem);
        }

        private void DeleteImage(ListViewItem imageListViewItem)
        {
            File.Delete(Path.Combine(this.ImagesPath, imageListViewItem.Name));
            this.CancelAllowed = string.Compare(imageListViewItem.Name, this._selectedItemName) != 0;
            this.lvw_images.Items.Remove(imageListViewItem);
            this.iml_associationFlags.Images.RemoveByKey(imageListViewItem.ImageKey);
        }

        private void LoadImage(FileInfo fileInfo)
        {
            Image image = Bitmap.FromFile(fileInfo.FullName);
            string key = image.GetHashCode().ToString();
            this.iml_associationFlags.Images.Add(key, image);
            image.Dispose();

            ListViewItem listViewItem = new ListViewItem();
            listViewItem.Name = fileInfo.Name;
            listViewItem.Text = Path.GetFileNameWithoutExtension(fileInfo.Name);
            listViewItem.ImageKey = key;

            this.lvw_images.Items.Add(listViewItem);
        }

        private void LoadImages()
        {
            this.iml_associationFlags.Images.Clear();
            this.lvw_images.Items.Clear();
            this.CreateNoneItem();

            if (!Directory.Exists(this.ImagesPath))
                Directory.CreateDirectory(this.ImagesPath);

            DirectoryInfo directoryInfo = new DirectoryInfo(this.ImagesPath);
            foreach (FileInfo fileInfo in directoryInfo.GetFiles())
                LoadImage(fileInfo);

            if (!string.IsNullOrEmpty(this.SelectedImage))
            {
                ListViewItem listViewItem = this.lvw_images.Items[this.SelectedImage];

                listViewItem.Selected = true;
                this.lvw_images.EnsureVisible(listViewItem.Index);
            }
        }

        private void RenameImage(ListViewItem imageListViewItem, string oldValue)
        {
            FileInfo flagFileInfo = new FileInfo(imageListViewItem.Name);
            string newName = oldValue +  flagFileInfo.Extension;
            string sourceFileName = Path.Combine(this.ImagesPath, flagFileInfo.Name);
            string destFileName = Path.Combine(this.ImagesPath, newName);
            

            File.Move(sourceFileName, destFileName);
            this.CancelAllowed = string.Compare(imageListViewItem.Name, this._selectedItemName) != 0;
            imageListViewItem.Name = newName;
            this.SelectedImage = newName;
        }

        #endregion

        #region Signed Event Methods

        private void FileChooser_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult != System.Windows.Forms.DialogResult.OK)
                e.Cancel = !this.CancelAllowed;
        }

        private void FileChooser_Load(object sender, System.EventArgs e)
        {
            this.LoadImages();
        }

        private void btn_import_Click(object sender, System.EventArgs e)
        {
            if (this.ofl_imageChooser.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                foreach (string filenames in this.ofl_imageChooser.FileNames)
                {
                    FileInfo flagFileInfo = new FileInfo(filenames);
                    this.CopyImage(flagFileInfo);
                    this.LoadImage(flagFileInfo);
                }
            }
        }

        private void lvw_images_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (this.lvw_images.SelectedItems.Count <= 0) return;
            this.RenameImage(this.lvw_images.SelectedItems[0], e.Label);
        }

        private void lvw_images_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right) return;
            if (this.lvw_images.SelectedItems.Count <= 0) return;
            if (string.Compare(this.lvw_images.SelectedItems[0].Name, "None") == 0) return;

            this.cms_image.Show(this.lvw_images, e.Location);
        }

        private void lvw_images_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (e.IsSelected)
                this.SelectedImage = e.Item.Name;

            this.btn_ok.Enabled = this.lvw_images.SelectedItems.Count > 0;
        }

        private void lvw_images_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Left) return;
            if (this.lvw_images.SelectedItems.Count <= 0) return;
            if (string.IsNullOrEmpty(this.lvw_images.SelectedItems[0].Name)) return;

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void tms_deleteFlag_Click(object sender, System.EventArgs e)
        {
            if (this.lvw_images.SelectedItems.Count <= 0) return;
            this.DeleteImage(this.lvw_images.SelectedItems[0]);
        }

        private void tsm_renameFlag_Click(object sender, System.EventArgs e)
        {
            if (this.lvw_images.SelectedItems.Count <= 0) return;
            this.lvw_images.SelectedItems[0].BeginEdit();
        }

        #endregion
    }
}
